package queueup
import (
    "time"
	"strings"
	"errors"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

//用户排队队列
type UserQueue struct {
	UserQueueFlowId int64  `orm:"column(user_flow_id);pk;auto" json:"user_flow_id" form:"user_flow_id"` //排队流水号
	PartnerId       int64    `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`           //商户ID
	StoreId         int64    `orm:"column(store_id)" json:"store_id" form:"store_id"`                 //门店ID
    TableTypeId     int64  `orm:"column(table_type_id)" json:"table_type_id" form:"table_type_id"`     //餐桌类型编号
	DataSource      int    `orm:"column(data_source)" json:"data_source" form:"data_source"`       //数据来源(0排队app;1取号设备2独立微信;3第三方微信;4菜板微信)
	UserId          int64    `orm:"column(user_id)" json:"user_id" form:"user_id"`                   //会员ID
	OpenId          string `orm:"column(open_id)" json:"open_id" form:"open_id"`                   //微信OpenId
	Mobile          string `orm:"column(mobile)" json:"mobile" form:"mobile"`                      //顾客手机
	OrderSeq        int    `orm:"column(order_seq)" json:"order_seq" form:"order_seq"`             //排序
	//ConsNum         int    `orm:"column(cons_num)" json:"cons_num" form:"cons_num"`              //消费人数
	QueueStatus     int    `orm:"column(queue_status)" json:"queue_status" form:"queue_status"`     //排队状态(0排队中;1排队完成;2排队取消;3排队过期)
	StatusAt     time.Time `orm:"column(status_at);type(datetime);null" json:"-" form:"-"`          //排队状态修改时间
	CreatedAt    time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"` //创建时间
	UpdatedAt    time.Time `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`     // 修改时间
}

// 进度提醒
type Tips struct {
    TipsId        int64 `orm:"column(tips_id);pk;auto" json:"tips_id" form:"tips_id"`           //预约单编号
	PartnerId     int64   `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`          //商户ID
	FrontPersons  int   `orm:"column(front_persons)" json:"front_persons" form:"front_persons"` //前面等待人数
	WaitTime      int   `orm:"column(wait_time)" json:"wait_time"`                              //预估等待时间
}

func init() {
	orm.RegisterModel(new(UserQueue))
}

func AddUserQueue(m *UserQueue) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}
func GetUserQueueById(id int64) (v *UserQueue, err error) {
	o := models.GetDefaultDB()
	v = &UserQueue{UserQueueFlowId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllUserQueues(storeIds []int64,query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*UserQueue, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(UserQueue))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	var lists []*UserQueue
	qs = qs.OrderBy(sortFields...)
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateUserQueueById(m *UserQueue, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := UserQueue{UserQueueFlowId: m.UserQueueFlowId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}
func DeleteUserQueue(id int64) (err error) {
	o := models.GetDefaultDB()
	v := UserQueue{UserQueueFlowId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}


// #region 根据用户微信openId查询是否存在正在排队中的信息

/*

#region 修改排队状态

        /// <summary>
        /// 修改排队状态
        /// </summary>
        /// <param name="merchantId">商户ID</param>
        /// <param name="queueNum">排队号</param>
        /// <param name="status">排队状态(0：排队中；1：排队完成；2：排队取消)</param>
        /// <returns>author：李晓乐 2014-9-15</returns>
        public static bool UpdateQueueStatus(decimal merchantId, string queueNum, EQueueStatus status)
        {
            #region sql及参数

            StringBuilder sql = new StringBuilder(" update Tab_User_Queue set  Queue_Status=@status,Status_Modify_Time= GETDATE(),Modify_Time= GETDATE(),Modify_User_Id = @merchantId ");
            sql.Append(" where Merchant_Id=@merchantId and Queue_No=@queueNum and Is_Delete=0 and Queue_Status = 0 and DATEDIFF(dd,GETDATE(),Create_Time)=0 ");
            SqlParameter[] parames =
            {
                new SqlParameter("@merchantId", merchantId),
                new SqlParameter("@queueNum", queueNum),
                new SqlParameter("@status", (decimal) status)
            };

            #endregion

            int flag = SqlDbHelper.ExecuteNonQuery(Config.ConnString, CommandType.Text, sql.ToString(), parames);
            return flag > 0;
        }

/// <summary>
        /// 查询最大的创建排队序号
        /// </summary>
        /// <param name="merid">商户ID</param>
        /// <returns>最大排队序号</returns>
        /// <remarks>李晓乐 add:2014-4-23</remarks>
        public static decimal GetMaxOrderSeqByID(decimal merid)
        {
            #region sql及参数

            string sql = @" select MAX(Order_Seq) Order_Seq from Tab_User_Queue where Merchant_Id = @m and Is_Delete = 0;";
            SqlParameter[] parmams =
            {
                new SqlParameter("@m", SqlDbType.Decimal, 10)
            };
            parmams[0].Value = merid;

            #endregion

            DataSet ds = SqlDbHelper.Execute(Config.ConnString, CommandType.Text, sql, parmams);
            List<UserQueue> list = null;
            if (ds != null && ds.Tables.Count > 0)
            {
                list = ConvertDataTable(ds.Tables[0], false);
                if (list != null && list.Count > 0)
                    return list[0].OrderSeq;
            }
            return 0;
        }

*/